<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { resetPwdAPI, logoutAPI } from '@/apis/user'
import { useUserStore } from '@/stores/userStore'

const pwdObj = ref({
    password: '',
    newPassword: '',
    type: 1
})

const verifyPwd = ref('')

const check = () => {
    const o = pwdObj.value
    if (o.password !== '' && o.newPassword !== '' && verifyPwd.value !== '') {
        return true
    }
    return false
}

const router = useRouter()
const userStore = useUserStore()
const resetPwd = async () => {
    if (!check()) {
        ElMessage({ type: 'warning', message: '请填写完整信息' })
        return
    }
    if (pwdObj.value.newPassword !== verifyPwd.value) {
        ElMessage({ type: 'warning', message: '两次填写的密码不一致' })
        return
    }
    const res = await resetPwdAPI({ ...pwdObj.value })
    if (res.code === 2000) {
        const response = await logoutAPI()
        if (response.code === 2000) {
            userStore.clearUserInfo()
        }
        ElMessage({ type: 'success', message: '密码已修改，请重新登录' })
        router.replace({ path: '/login' })
    }
}
</script>

<template>
<div class="alterPwd-page">
    <div class="page-title">修改密码</div>
    <div class="page-body">
        <div>
            <div class="label">原密码：</div>
            <div class="ipt"><input type="password" v-model="pwdObj.password"></div>
        </div>
        <div>
            <div class="label">新密码：</div>
            <div class="ipt"><input type="password" v-model="pwdObj.newPassword"></div>
        </div>
        <div>
            <div class="label">确认新密码：</div>
            <div class="ipt"><input type="password" v-model="verifyPwd"></div>
        </div>
        <div>
            <div class="label"></div>
            <a href="javascript:;" class="alter-btn" @click="resetPwd">修改密码</a>
        </div>
    </div>
</div>
</template>

<style scoped lang='scss'>
.alterPwd-page {
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: #fff;
}

.page-title {
    font-size: 21px;
    padding: 15px 0;
    border-bottom: 1px solid #e8e8e8;
}

.page-body {
    margin-top: 40px;

    >div {
        display: flex;
        align-items: center;
        margin-bottom: 30px;

        &:last-child {
            margin-bottom: 0;
        }
    }

    .label {
        width: 100px;
        color: #666;
        font-weight: bold;
    }

    .ipt {
        width: 300px;
        height: 35px;
        border: 1.5px solid #d8d8d8;
        border-radius: 5px;

        input {
            width: 100%;
            height: 100%;
            font-size: 16px;
            padding: 0 10px;
            border-radius: 5px;
        }
    }

    .alter-btn {
        display: block;
        width: 100px;
        height: 35px;
        line-height: 35px;
        border-radius: 4px;
        font-size: 14px;
        color: #fff;
        background-color: #39bf3e;
        text-align: center;
    }
}
</style>
